package com.mk.magic_c.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mk.magic_c.dto.UserLoginVo;
import com.mk.magic_c.dto.UserRegisterVo;
import com.mk.magic_c.model.LoginTicket;
import com.mk.magic_c.service.LoginTicketService;
import com.mk.magic_c.service.UserService;
import com.mk.magic_c.utils.BusinessConstant;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Magic Kong
 * @since 2021-10-02
 */
@Controller
@RequestMapping("/user")
public class UserController implements BusinessConstant {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginTicketService loginTicketService;

    @GetMapping("register")
    public String toRegisterPage(Model model) {
        // 初始化页面属性，防止thymeleaf解析空指针异常
        model.addAttribute("user", new UserRegisterVo());
        model.addAttribute("error", new HashMap<>());
        return "site/register";
    }

    @PostMapping("register")
    public String doRegister(UserRegisterVo user, Model model) {
        Map<String, Object> result = userService.register(user);

        if (result.size() == 0) {
            // 跳转到操作成功页面，提示用户已发送激活邮件，并跳转到登陆页面
            model.addAttribute("message", "账号注册成功，我们已向您发送激活邮件，请注意查收");
            model.addAttribute("redirectUrl", "/user/login");
            return "site/operate-result";
        }
        // 否则返回注册页面显示错误提示

        model.addAttribute("error", result);
        model.addAttribute("user", user);
        return "site/register";
    }

    @ApiOperation("激活账号")
    @GetMapping("active/{id}/{activationCode}")
    public String activation(@PathVariable("id") Integer id,
                             @PathVariable("activationCode") String activationCode,
                             Model model) {
        int result = userService.activeAccount(id, activationCode);

        if (result == BusinessConstant.ACTIVE_SUCCESS) {
            // 激活成功，跳转到登陆页面
            model.addAttribute("message", "您的账号已经激活成功,可以正常使用了!");
            model.addAttribute("redirectUrl", "/user/login");
        } else if (result == BusinessConstant.ACTIVE_DUPLICATION) {
            // 重复激活, 跳转到首页
            model.addAttribute("message", "您的账号已经激活成功，请不要重复激活");
            model.addAttribute("redirectUrl", "/index");
        } else {
            // 激活失败，跳转到首页
            model.addAttribute("message", "无效的激活链接");
            model.addAttribute("redirectUrl", "/index");
        }
        return "site/operate-result";
    }

    @GetMapping("login")
    public String toLoginPage(Model model) {
        model.addAttribute("user", new UserLoginVo());
        return "site/login";
    }

    @PostMapping("login")
    public String doLogin(UserLoginVo userLoginVo, HttpServletResponse response, HttpSession session, Model model) {
        // 检查验证码是否正确
        String kaptcha_code = (String) session.getAttribute("kaptcha_code");
        if (!StrUtil.equalsIgnoreCase(userLoginVo.getKaptcha(), kaptcha_code)) {
            model.addAttribute("kaptchaError", "验证码错误");
            model.addAttribute("user", userLoginVo);
            return "site/login";
        }

        // 校验用户名和密码
        Map<String, String> result = userService.login(userLoginVo);
        if (result.containsKey("loginTicket")) {
            Cookie cookie = new Cookie("ticket", result.get("loginTicket"));
            cookie.setMaxAge(userLoginVo.getRememberMe() ? REMEMBER_ME_ON : REMEMBER_ME_OFF);
            cookie.setPath("/magic_c");
            response.addCookie(cookie);
            return "redirect:/index";
        }
        // 校验失败，返回错误信息
        model.addAttribute("usernameError", result.getOrDefault("usernameError", ""));
        model.addAttribute("passwordError", result.getOrDefault("passwordError", ""));
        model.addAttribute("user", userLoginVo);
        return "site/login";
    }

    @GetMapping("logout")
    public String doLogout(HttpServletResponse response, @CookieValue("ticket") String ticket) {
        LoginTicket ticket1 = loginTicketService.getOne(new QueryWrapper<LoginTicket>().eq("ticket", ticket));
        ticket1.setStatus(1);
        loginTicketService.updateById(ticket1);

        // 移除cookie，浏览器关闭后，该cookie消失
        Cookie ticket2 = new Cookie("ticket", null);
        ticket2.setMaxAge(0);
        ticket2.setPath("/magic_c");
        response.addCookie(ticket2);

        return "redirect:/user/login";
    }
}

